package com.ang.juc.nt.set;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.IntStream;

public class CopyOnWriteSetTest {

    private static Set set = new HashSet();
    private static CopyOnWriteArraySet arraySet = new CopyOnWriteArraySet();

    public static void main(String[] args) throws InterruptedException {
//        test1();
        test2();
    }

    public static void test1() throws InterruptedException {
        List<Thread> lt = new ArrayList<>();
        IntStream.range(0,10).forEach(i->{
            Thread thread = new Thread(() -> {
                IntStream.range(0,100).forEach(j->{
                    set.add(i+"-"+j);
                });
            });
            thread.start();
            lt.add(thread);
        });

        for (Thread thread : lt) {
            thread.join();
        }

        System.out.println(set.size());
    }

    public static void test2() throws InterruptedException {
        List<Thread> lt = new ArrayList<>();
        IntStream.range(0,10).forEach(i->{
            Thread thread = new Thread(() -> {
                IntStream.range(0,100).forEach(j->{
                    arraySet.add(i+"-"+j);
                });
            });
            thread.start();
            lt.add(thread);
        });

        for (Thread thread : lt) {
            thread.join();
        }

        System.out.println(arraySet.size());
    }
}
